<template>
  <div class="box">
    <div class="header">
      <input type="text" placeholder="请评论" v-model="content" autofocus autocomplete="off" />
      <button @click="pub">发布</button>
    </div>

    <ul id="list">
      <li v-for="(item, index) in comments" :key="item.id">
        <span>{{ item.content }}</span>
        <span class="del" @click="delComment(index)">删除</span>
      </li>
    </ul>
    <div>共{{ comments.length }}条评论</div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'

let comments = ref([])
let content = ref('')

onMounted(() => {
  // 获取本地存储的数据，赋值给comments响应式变量
  comments.value = JSON.parse(localStorage.getItem('comments') || '[]')
})


// 发布评论
const pub = () => {
  let item = { id: Date.now(), content: content.value }
  comments.value.push(item)
  content.value = ''
}

// 删除评论
const delComment = (index) => {
  if (confirm('确认删除吗')) {
    comments.value.splice(index, 1)
  }
}

// 监听评论数组的变化
watch(comments, (newV) => {
  console.log('监听到了')
  // 将数据持久化到本地存储
  localStorage.setItem('comments', JSON.stringify(newV))
}, { deep: true })

</script>

<style>
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.box {
  width: 300px;
  margin: 50px auto;
}

.box .header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.box .header input {
  height: 40px;
  outline: 0;
}

.box .header button {
  width: 80px;
  /* flex: 1; */
}

.box ul li {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 40px;
  list-style-type: none;
  border-bottom: 1px solid #333;
}

.box ul li .del {
  color: blue;
  cursor: pointer;
}
</style>